# auth.py
from flask import Blueprint, jsonify, request
from flask_cors import CORS, cross_origin
from flask_jwt_extended import get_jwt_identity, jwt_required
import flaskapp.services.dictionary as service
import logging

logger = logging.getLogger(__name__)
dictionary_bp = Blueprint('dictionary', __name__)


@dictionary_bp.route('/api/dictionary', methods=['POST'])
@jwt_required()
def createDict():
    try:
        category = request.json.get("category", None)
        key = request.json.get("key", None)
        value = request.json.get("value", None)

        ret = service.insert(category=category, key=key, value=value)
        response = jsonify({"code": 0, "message": ret})
        return response
    except Exception as e:
        logger.error(f"Error getting data: {e}")
        return jsonify({"code": -1, "message": e.args})

@dictionary_bp.route('/api/dictionary', methods=['GET'])
@jwt_required()
def getDict():
    try:
        pageIndex = int(request.values.get('pageIndex',1))
        pageSize = int(request.values.get('pageSize',10))
        ret = service.get(page=pageIndex, per_page=pageSize,
                        category=request.values.get('category'))
        # print(ret)
        response = jsonify({"code": 0, "data": ret})
        return response
    except Exception as e:
        logger.error(f"Error getting data: {e.args}")
        return jsonify({"code": -1, "message": e.args})


@dictionary_bp.route('/api/dictionary/<id>', methods=['DELETE'])
@jwt_required()
def deleteDict(id):
    try:
        ret = service.delete(id)
        response = jsonify({"code": 0, "data": ret})
        return response
    except Exception as e:
        logger.error(f"Error getting data: {e}")
        return jsonify({"code": -1, "message": e.args})
   
@dictionary_bp.route('/api/dictionary/<string:category>', methods=['GET'])
def get_category_kv(category):
    try:
        logger.info(f"Request received for dictionary items in category: {category}")
        data = service.dict_category_kv(category)
        return jsonify({"code": 0, "data": data})
    except Exception as e:
        logger.error(f"Error getting dictionary items for category {category}: {e}")
        return jsonify({"error": "Failed to get dictionary items"})
